<template>
	<view class="container">
		<!-- 搜索栏 -->
		<view class="search-bar">
			<button @tap="startScan">扫码</button>
			<input
				v-model="billNoInput"
				placeholder="请输入单据编号"
				class="search-input"
				@confirm="fetchData"
			/>
			<button class="search-btn" @tap="fetchData">查询</button>
		</view>

		<!-- 操作按钮组 -->
		<view class="action-bar">
			<button @tap="clearAll">清除</button>
			<button @tap="handleAddDetail">添加</button>
			<button @tap="handleUpdateDetail">修改</button>
			<button @tap="handleAudit">审核</button>
		</view>
		
		<!-- 单据列表 -->
		<scroll-view scroll-y class="list-container">
			<view 
				v-for="(group, index) in productGroups" 
				:key="index"
				class="group-container"
			>
				<text class="group-title">{{ group.title }}</text>
				
				<radio-group @change="radioChange">
					<view
						v-for="product in group.products"
						:key="product.id"
						class="product-card"
						
					>
						<!-- 单选框 -->
						<radio :value="product.billNo" :checked="selectedBillNo === product.billNo" />
				
						<!-- 单据信息展示 -->
						<view class="card-header">
							<text class="bill-no">{{ product.billNo }}</text>
							<text class="status-tag" :class="statusClass(product)">
								单据状态：{{ product.billStatus }}
							</text>
						</view>          
						<view class="detail-row">
							<text>单据类型：{{ product.billType }}</text>	
							<text>物料名称: {{ product.goodsName }}</text>
							<text>库存数量: {{ product.qty }} {{ product.unitCode }}</text>			
							<text>指定仓库：{{ product.workingAreaCode }}</text><p></p>
							<text>车间任务单号：{{ product.productBillNo }}</text><p></p>
							<text>物料编号：{{ product.goodsCode }}</text><p></p>
							<text>可进仓数量：{{ product.qty }}</text><p></p>
							<text>库位：{{ product.waLocationCode }}</text><p></p>
							<text>完工工序：{{ product.wpCode }}</text><p></p>
							<text>图号版本-规格：{{ product.designNumberVerSpec }}</text><p></p>
						</view>
						<!-- 文件操作区域 -->
						<view class="file-section">
							<image
								v-if="product.imageUrl"
								:src="product.imageUrl"
								mode="aspectFill"
								lazy-load
								class="preview-image"
								@error="handleImageError(product)"
							/>
							<button 
								v-if="product.pdfUrl"
								class="pdf-btn"
								@tap.stop="handleDownloadPdf(product)"
							>
								查看 PDF 图
							</button>
						</view>
					</view>
				</radio-group>
			</view>
		</scroll-view>
	</view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import type { Product } from '../models/Product'
import type { ProductGroup } from '../models/ProductGroup'
import { LAN_URL } from '@/pages/config/global'
import { DOWNLOAD_BASE } from '@/pages/config/global'

// 常量配置
const AUDIT_URL = '/produceRepair/audit'
const POWER_URL = '/check/checkPower'
const FETCH_URL = '/produceRepair/findByNo'
const moduleID = ref('工序进仓单录入')

// 响应式状态
const billNoInput = ref('')
const productGroups = ref<ProductGroup[]>([])
const selectedBillNo = ref<string | null>(null)
const userID = ref<string | null>(null)
const userName = ref<string | null>(null)
const scanResult = ref('')

const billNoGroup = ref([])

onMounted(() => {
	loadUserInfo();
	uni.removeStorageSync('product')
});

/* 业务逻辑 */
/* 加载用户信息 */
const loadUserInfo = () => {
	const user = uni.getStorageSync('user');
	if (user) {
		userID.value = user.id;
		userName.value = user.name;
	}
};

/* 获取数据 */
const fetchData = async () => {
	if (!userID.value || !userID.value.trim()) {
		uni.showToast({ title: '用户数据异常', icon: 'none' })
		return;
	}
	if (!billNoInput.value || !billNoInput.value.trim()) {
		uni.showToast({ title: '请输入单据编号', icon: 'none' })
		return;
	}
	console.log(productGroups.value)
	//每次查询都清空后重新查询
	const pg = ref<ProductGroup[]>([])
	productGroups.value= pg.value
	console.log(productGroups.value)
	console.log(billNoGroup.value.length)
	
	if(billNoGroup.value.length>0){
		
		for (var i = 0; i < billNoGroup.value.length; i++) {
			console.log(i)
			
			console.log("bill_no : "+billNoGroup.value[i])
			const {data} = await uni.request({
				url:`${LAN_URL}${FETCH_URL}`,
				method:'POST',
				data:{billNo:billNoGroup.value[i]}
			})
			
			if (!data) {
				uni.showToast({ title: '没有查询到数据', icon: 'error' })
				return;
			}
			
			
			const product = mapToProduct(data)
			//console.log(product)
			uni.setStorageSync('product', product)
			uni.setStorageSync('billNo', product.billNo)
			for (let i = 0; i <= productGroups.value.length; i++){
				const group = productGroups.value[i]
				if(i == productGroups.value.length){
					console.log("2")
					productGroups.value.unshift(createProductGroup(product))
					break;
				}
				if(group.products[i].billNo == billNoInput.value){
					break;
				}
			}
			
		}
	}
	//try {
		const { data } = await uni.request({
			url: `${LAN_URL}${FETCH_URL}`,
			method: 'POST',
			data: { billNo: billNoInput.value }
		})
		if (!data) {
			uni.showToast({ title: '没有查询到数据', icon: 'error' })
			return;
		}
		
		//将成功查询到的bill_no 存进数组
		billNoGroup.value.push(billNoInput.value)
		
		const product = mapToProduct(data)
		//console.log(product)
		uni.setStorageSync('product', product)
		uni.setStorageSync('billNo', product.billNo)
		for (let i = 0; i <= productGroups.value.length; i++){
			const group = productGroups.value[i]
			if(i == productGroups.value.length){
				console.log("1")
				productGroups.value.unshift(createProductGroup(product))
				break;
			}
			if(group.products[i].billNo == billNoInput.value){
				break;
			}
			
		}
		//productGroups.value.unshift(createProductGroup(product))

		uni.showToast({ title: '查询成功' })
	//} catch (error) {
	//	handleNetworkError(error)
	//}
}

/* 数据转换 */
const mapToProduct = (apiData: any): Product => ({
	id: apiData.id,
	billNo: apiData.billNo,
	billStatus: apiData.billStatus,
	billType: apiData.billType,
	workingAreaCode: apiData.workingAreaCode,
	productBillNo: apiData.productBillNo,
	goodsCode: apiData.goodsCode,
	qty: Number(apiData.qty),
	waLocationCode: apiData.waLocationCode,
	wpCode: apiData.wpCode,
	goodsName: apiData.goodsName,
	designNumberVerSpec: apiData.designNumberVerSpec,
	unitCode: apiData.unitCode,
	remark: apiData.remark,
	imageUrl: apiData.imageUrl ? `${DOWNLOAD_BASE}${apiData.imageUrl}` : undefined,
	pdfUrl: apiData.pdfUrl ? `${DOWNLOAD_BASE}${apiData.pdfUrl}` : undefined
})
const createProductGroup = (product: Product): ProductGroup => ({
	title: `订单 ${productGroups.value.length + 1}`,
	products: [product]
})

/* 交互逻辑 */
/* 选择订单 */
const radioChange = (event: any) => {
	console.log(selectedBillNo.value)
	selectedBillNo.value = event.detail.value;
	// fetchData();
};

/* 审核 */
const handleAudit = async () => {
	if (!selectedBillNo.value) {
		uni.showToast({ title: '请先选择单据', icon: 'none' })
		return
	}
	uni.showModal({
		title: '提示',
		content: '是否审核？',
		success: (res) => {
			if (!res.confirm) {
				uni.showToast({
					title: '用户取消了审核',
					icon: 'none'
				})
				return;
			}
		}
	})
	
	try {
		if (userID && userID != null ) {
			const { data } = await uni.request({
				url: `${LAN_URL}${POWER_URL}`,
				method:'POST',
				header: { "Content-Type": "application/x-www-form-urlencoded" },
				data: `userID=${userID.value}&moduleID=${moduleID.value}&subPower=审核`
			})
			if (data) {
				const { data } = await uni.request({
					url: `${LAN_URL}${AUDIT_URL}`,
					method: 'POST',
					data: {userID: userID.value, userName: userName.value, billNo: selectedBillNo.value, modeID: '审核'}
				})
				if (data === 1) {
					uni.showToast({ title: '单据已审核，不可再审核', icon: 'none' })
				} else if (data === 2) {
					uni.showToast({ title: '审核成功' })
				} else {
					uni.showToast({ title: '审核异常' })
				}
			}else {
				uni.showToast({ title: '你没有权限执行此操作', icon: 'none' })
			}
		}
	} catch (error) {
		handleNetworkError(error)
	}
}

/* 文件操作 */
/* 获取原始文件名 */
const getFileNameFromUrl = (url: string) => {
  //处理带参数的URL
  const cleanUrl = url.split('?')[0]
  //获取最后一个斜杠后的内容
  const parts = cleanUrl.split('/')
  return parts[parts.length - 1] || `document_${Date.now()}.pdf` // 默认文件名
}

/* PDF下载 */
const handleDownloadPdf = async (product: Product) => {
	if (!product.pdfUrl) return;

	try {
		const fileName = getFileNameFromUrl(product.pdfUrl)
		const saveDir = '_doc/uniapp_save/'
		
		const { tempFilePath } = await uni.downloadFile({
			url: product.pdfUrl
		})
		let savedPath = '';
		
		// #ifdef MP-WEIXIN
		savedPath = `${uni.env.USER_DATA_PATH}/${Date.now()}.pdf`
		// #endif
	
		// #ifdef APP-PLUS
		savedPath = `${plus.io.convertLocalFileSystemURL(saveDir)}${fileName}`
		// #endif
		uni.openDocument({
			filePath: savedPath,
			success: () => {
			    console.log("PDF文件已成功不下载打开");
			},
			fail() {
				uni.saveFile({
					tempFilePath, filePath: savedPath, success(res) {
						console.log("res:" + res.savedFilePath)
						plus.io.resolveLocalFileSystemURL(res.savedFilePath,
							(entry) => {
								console.log("实际存储路径:", "fullPath" + entry.fullPath);
								console.log("savedPath:",savedPath)
								//重命名文件
								plus.io.resolveLocalFileSystemURL(saveDir, (dirEntry) => {
								    entry.moveTo(dirEntry, fileName, (newEntry) => {
								        console.log("文件已重命名:", newEntry.fullPath);
									}, (err) => {
										console.error("文件重命名失败:", err);
									});
								});
							}, 
							(err) => {
								console.log("找不到文件:", err);
							}
						);
						uni.openDocument({
							filePath: res.savedFilePath,
							success: () => {
								console.log("PDF文件已成功打开");
							},
							fail: (err) => {
								console.error("PDF打开失败:", err);
							}
						});
					},fail(err) {
						uni.showToast({ title: '文件不存在', icon: 'error' })
						console.log(err)
					}
				})
			}
		})
	} catch (error) {
		uni.showToast({ title: '文件打开失败', icon: 'none' })
	}
}

/* 扫码 */
const startScan = async () => {
  try {
    const res = uni.scanCode({
		scanType: ['qrCode', 'barCode'],
		onlyFromCamera: true,
		success: (result) => {
			handleScanResult(result)
		},
		fail: (err) => {
			handleScanError(err)
		}
	})
  } catch (error) {
    handleScanError(error)
  }
}
/* 扫码结果处理 */
const handleScanResult = (result: UniApp.ScanCodeSuccessRes) => {
	billNoInput.value = result.result
	console.log("scanResult:", billNoInput.value)
	console.log("resule:", result.result)
	if (result.scanType === 'EAN_13') {
		console.log("1")
	}
	fetchData();
}
/* 扫码错误 */
const handleScanError = (error: any) => {
	console.error('扫码失败:', error)
	uni.showToast({
		title: '扫码失败，请重试',
		icon: 'none'
  })
}

/* 工具方法 */
const clearAll = () => {
	productGroups.value = []
	selectedBillNo.value = null
	billNoInput.value = null;
	uni.removeStorageSync('product')
	uni.removeStorageSync('billNo')
}
/* 网络错误 */
const handleNetworkError = (error: any) => {
	console.error('网络请求失败:', error)
	uni.showToast({ title: '服务器连接失败', icon: 'none' })
}
/* 图片加载失败显示图 */
const handleImageError = (product: Product) => {
	product.imageUrl = '/static/images/placeholder.png'
}

/* 单号状态显示 */
const statusClass = (product: Product) => ({
	'status-passed': product.billStatus === '已通过',
	'status-pending': product.billStatus === '待审核',
	'status-rejected': product.billStatus === '已拒绝'
})
/* 添加 */
const handleAddDetail = async () => {
	try {
		if (userID && userID != null ) {
			const { data } = await uni.request({
				url: `${LAN_URL}${POWER_URL}`,
				method:'POST',
				header: { "Content-Type": "application/x-www-form-urlencoded" },
				data: `userID=${userID.value}&moduleID=${moduleID.value}&subPower=增加`
			})
			if (data) {
				uni.removeStorageSync('product')
				selectedBillNo.value = null;
				uni.navigateTo({ url: '/pages/productRepairDetail/productRepairDetail' })
			}else {
				uni.showToast({ title: '你没有权限执行此操作', icon: 'none' })
			}
		}
	} catch (error) {
		handleNetworkError(error)
	}
}
/* 修改 */
const handleUpdateDetail = async () => {
	console.log(selectedBillNo.value)
	if (!selectedBillNo.value) {
		uni.showToast({ title: '请先选择单据', icon: 'none' })
		return
	}
	
	try {
		if (userID && userID != null ) {
			const { data } = await uni.request({
				url: `${LAN_URL}${POWER_URL}`,
				method:'POST',
				header: { "Content-Type": "application/x-www-form-urlencoded" },
				data: `userID=${userID.value}&moduleID=${moduleID.value}&subPower=保存`
			})
			if (data) {
				
				const { data } = await uni.request({
					url: `${LAN_URL}${AUDIT_URL}`,
					method: 'POST',
					data: {userID: userID.value, userName: userName.value, billNo: selectedBillNo.value, modeID: '保存'}
				})
				
				if (data === 1) {
					uni.showToast({ title: '单据已审核，不可再修改', icon: 'none' })
				/* } else if (data === 0) {
					uni.showToast({ title: '数据异常', icon: 'none' }) */
				} else {
					uni.navigateTo({ url: '/pages/productRepairDetail/productRepairDetail' });
				}
			}else {
				uni.showToast({ title: '你没有权限执行此操作', icon: 'none' })
			}
		}
	} catch (error) {
		handleNetworkError(error)
	}
}
</script>

<style lang="scss" scoped>
.container {
	padding: 20rpx;
	background-color: #f5f5f5;
}

.search-bar {
	display: flex;
	margin-bottom: 30rpx;
	gap: 20rpx;

	.search-input {
		flex: 1;
		height: 80rpx;
		padding: 0 30rpx;
		border: 1rpx solid #ddd;
		border-radius: 40rpx;
	}

	.search-btn {
		width: 160rpx;
		background: #007aff;
		color: white;
		border-radius: 40rpx;
	}
}

.product-card {
	background: white;
	margin: 20rpx 0;
	padding: 30rpx;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.08);

	&.selected {
		border: 2rpx solid #007aff;
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 20rpx;

		.bill-no {
			font-weight: bold;
			font-size: 32rpx;
		}

		.status-tag {
			padding: 8rpx 16rpx;
			border-radius: 8rpx;
			font-size: 24rpx;

			&.status-passed { background: #e8f5e9; color: #2e7d32; }
			&.status-pending { background: #fff3e0; color: #ef6c00; }
			&.status-rejected { background: #ffebee; color: #c62828; }
		}
	}

	.detail-row {
		display: flex;
		flex-direction: column;
		gap: 12rpx;
		color: #666;
		margin-bottom: 30rpx;
	}

	.preview-image {
		width: 100%;
		height: 300rpx;
		border-radius: 8rpx;
		margin-top: 20rpx;
		background: #f0f0f0;
	}

	.pdf-btn {
		margin-top: 20rpx;
		background: #4caf50;
		color: white;
	}
}

.action-bar {
	display: flex;
	gap: 20rpx;
	margin: 30rpx 0;

	button {
		flex: 1;
		height: 80rpx;
		border-radius: 40rpx;
		background: #f0f0f0;

		&:active {
			background: #e0e0e0;
		}
	}
}
</style>